package com.lzz.bottomencapsulation.customview.selectimage;

import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.lzz.bottomencapsulation.R;
import com.lzz.bottomencapsulation.customview.selectimage.utils.PermissionUtils;
import com.lzz.bottomencapsulation.customview.selectimage.utils.Utils;
import com.lzz.bottomencapsulation.utils.AppUtils;

import java.io.File;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;

/**
 * 图片选择器activity
 */
public class ImageSelectorActivity extends FragmentActivity implements ImageSelectorFragment
        .Callback, PermissionUtils.PermissionGrant {

    public static final String EXTRA_RESULT = "select_result";//选择成功标识

    private ImageConfig imageConfig;//配置参数

    private ArrayList<String> pathList = new ArrayList<>();//默认选择的图片

    private TextView title_text;//标题

    private TextView submitButton;//完成按钮

    private FragmentTransaction fragmentTransaction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.imageselector_activity);
        imageConfig = ImageSelector.getImageConfig();
        fragmentTransaction = getSupportFragmentManager().beginTransaction();
        submitButton = (TextView) findViewById(R.id.title_right);
        title_text = (TextView) findViewById(R.id.title_text);
        init();
        PermissionUtils.requestMultiPermissions(this, this);
    }

    private void init() {
        pathList = imageConfig.getPathList();
//        返回键监听
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setResult(RESULT_CANCELED);//取消
                exit();
            }
        });
//设置按钮显示
        if (pathList == null || pathList.size() <= 0) {
            //       无默认选中图片
            submitButton.setText(R.string.finish);
            submitButton.setEnabled(false);
        } else {
//            有默认选中图片
            submitButton.setText((getResources().getText(R.string.finish)) + "(" + pathList.size
                    () + "/" + imageConfig.getMaxSize() + ")");
            submitButton.setEnabled(true);
        }

//        完成按钮点击事件
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (pathList != null && pathList.size() > 0) {
                    Intent data = new Intent();
                    data.putStringArrayListExtra(EXTRA_RESULT, pathList);
                    setResult(RESULT_OK, data);
                    exit();
                }
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ImageSelector.IMAGE_CROP_CODE && resultCode == RESULT_OK) {
            Intent intent = new Intent();
            pathList.add(cropImagePath);
            intent.putStringArrayListExtra(EXTRA_RESULT, pathList);
            setResult(RESULT_OK, intent);
            exit();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //    销毁activity
    private void exit() {
        finish();
    }

    private String cropImagePath;

    private void crop(String imagePath, int aspectX, int aspectY, int outputX, int outputY) {
        File file;
        if (Utils.existSDCard()) {
            file = new File(Environment.getExternalStorageDirectory() + imageConfig.getFilePath()
                    , Utils.getImageName());
        } else {
            file = new File(getCacheDir(), Utils.getImageName());
        }
        cropImagePath = file.getAbsolutePath();
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(Uri.fromFile(new File(imagePath)), "image/*");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(this, AppUtils.getPackageName(this)+".android7.fileprovider",
                    new File(imagePath));
            intent.setDataAndType(contentUri, "image/*");
        } else {
            intent.setDataAndType(Uri.fromFile(new File(imagePath)), "image/*");
        }
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", aspectX);
        intent.putExtra("aspectY", aspectY);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(intent, ImageSelector.IMAGE_CROP_CODE);
    }

    @Override
    public void onSingleImageSelected(String path) {
        if (imageConfig.isCrop()) {
            crop(path, imageConfig.getAspectX(), imageConfig.getAspectY(), imageConfig.getOutputX
                    (), imageConfig.getOutputY());
        } else {
            Intent data = new Intent();
            pathList.add(path);
            data.putStringArrayListExtra(EXTRA_RESULT, pathList);
            setResult(RESULT_OK, data);
            exit();
        }
    }

    @Override
    public void onImageSelected(String path) {
        if (!pathList.contains(path)) {
            pathList.add(path);
        }
        if (pathList.size() > 0) {
            submitButton.setText((getResources().getText(R.string.finish)) + "(" + pathList.size
                    () + "/" + imageConfig.getMaxSize() + ")");
            if (!submitButton.isEnabled()) {
                submitButton.setEnabled(true);
            }
        }
    }

    @Override
    public void onImageUnselected(String path) {
        if (pathList.contains(path)) {
            pathList.remove(path);
            submitButton.setText((getResources().getText(R.string.finish)) + "(" + pathList.size
                    () + "/" + imageConfig.getMaxSize() + ")");
        } else {
            submitButton.setText((getResources().getText(R.string.finish)) + "(" + pathList.size
                    () + "/" + imageConfig.getMaxSize() + ")");
        }
        if (pathList.size() == 0) {
            submitButton.setText(R.string.finish);
            submitButton.setEnabled(false);
        }
    }

    @Override
    public void onCameraShot(File imageFile) {

        if (imageFile != null) {
            if (imageConfig.isCrop()) {
                crop(imageFile.getAbsolutePath(), imageConfig.getAspectX(), imageConfig
                        .getAspectY(), imageConfig.getOutputX(), imageConfig.getOutputY());
            } else {
                Intent data = new Intent();
                pathList.add(imageFile.getAbsolutePath());
                data.putStringArrayListExtra(EXTRA_RESULT, pathList);
                setResult(RESULT_OK, data);
                exit();
            }
        }
    }

    @Override
    public boolean getgetIsCameraSelectedImg() {
        if (pathList.size() < imageConfig.getMaxSize()) {
            return true;
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults,
                this);
    }

    @Override
    public void onPermissionGranted(int requestCode) {
        if (requestCode == PermissionUtils.CODE_MULTI_PERMISSION) {
            fragmentTransaction.add(R.id.image_grid, new ImageSelectorFragment())
                    .commitAllowingStateLoss();
        } else {
            Toast.makeText(this, "无权限,无法进行该项服务，请授予权限", Toast.LENGTH_SHORT).show();
            exit();
        }
    }
    @Override
    public Resources getResources() {
        // 字体大小不跟随系统
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }
}